package com.wanmait.employment.webController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.github.pagehelper.PageInfo;
import com.wanmait.employment.entity.*;
import com.wanmait.employment.mapper.CompanyMapper;
import com.wanmait.employment.service.CompanyService;
import com.wanmait.employment.util.AjaxResult;
import com.wanmait.employment.util.JWTUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.tomcat.util.security.MD5Encoder;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("web/company")
public class WebCompanyController {
        @Resource
        private CompanyService companyService;
        @Resource
        private CompanyMapper companyMapper;
        @Resource
        private RedisTemplate<String,Object> redisTemplate;
        @Resource
        private StringRedisTemplate stringRedisTemplate;
        @Value("${hash.algorithmName}")
        private String algorithmName;
        @Value("${hash.iterations}")
        private Integer iterations;

        @GetMapping("register")
        public AjaxResult register(String tel,String password) throws JsonProcessingException {
                Company company=new Company();
                company.setCompanyPassword(password);
                company.setCompanyTel(tel);

                ObjectMapper objectMapper =new ObjectMapper();
                String jsonstr= objectMapper.writeValueAsString(company);
                stringRedisTemplate.opsForValue().set("company",jsonstr);
                String salt=UUID.randomUUID().toString().replaceAll("-","");
                company.setSalt(salt);
                SimpleHash simpleHash=new SimpleHash(algorithmName,company.getCompanyPassword(),salt,iterations);
                company.setCompanyPassword(simpleHash.toString());
                companyService.register(company);
                Company company1 = companyService.login(company);
                if(company1==null){
                        return AjaxResult.error(10001,"登录失败了");
                }
                //生成token
                Map<String,String> claims = new HashMap<>();
                claims.put("username",company.getCompanyName());
                claims.put("name",company.getCompanyTel());
                String token  = JWTUtils.createToken(company.getId()+"",60,company.getCompanyPassword(),claims);

                //使用token作为键，把admin用户对象放到redis中，设置过期时间和token的过期时间一致
                redisTemplate.opsForValue().set("token:"+token,company1,60, TimeUnit.MINUTES);

                company1.setCompanyPassword(null);
                return AjaxResult.success("注册成功").put("token",token).put("company",company1);
        }
        @GetMapping("login")
        public AjaxResult login(String tel,String userpass){
                Company company=new Company();
                company.setCompanyTel(tel);
                company.setCompanyPassword(userpass);
                Company companys= companyMapper.selecttel(company.getCompanyTel());
                //加密
                SimpleHash simpleHash = new SimpleHash(algorithmName,company.getCompanyPassword(),companys.getSalt(),iterations);
                company.setCompanyPassword(simpleHash.toString());
                Company company1 = companyService.login(company);
                if(company1==null){
                        return AjaxResult.error(10001,"登录失败了");
                }
                //生成token
                Map<String,String> claims = new HashMap<>();
                claims.put("companyname",company.getCompanyTel());
                claims.put("company",company.getCompanyPassword());
                String token  = JWTUtils.createToken(company.getId()+"",60,company.getCompanyPassword(),claims);

                //使用token作为键，把admin用户对象放到redis中，设置过期时间和token的过期时间一致
                redisTemplate.opsForValue().set("token:"+token,company1,60, TimeUnit.MINUTES);

                company1.setCompanyPassword(null);
                return AjaxResult.success("登录成功").put("token",token).put("company",company1);
        }

        //公司主页
        @GetMapping("selectOne")
        public AjaxResult selectOne(Integer companyId){
               Company company=companyService.selectOne(companyId);
                return AjaxResult.success("success",company);
        }
        //     获取公司信息
        @GetMapping("getCompanyInfo")
        public AjaxResult getCompanyInfo(String firmName){
                Company company=companyService.findByFirmName(firmName);
                if(company.getId()!=null){
                        return AjaxResult.success("success").put("company",company);
                }else{
                        return AjaxResult.success("info");
                }

        }
//公司筛选
        @GetMapping("screen")
        public AjaxResult screen(String city,String companyType,String companyScale,  String financingStage,int pageNum, int pageSize){
                System.out.println("////////////////"+city);
                System.out.println("++++++++++++++++"+companyType);
                System.out.println("----------------"+companyScale);
                System.out.println("****************"+financingStage);
                PageInfo<Company> companyPageInfo=companyService.selectAll(city,companyType,companyScale,financingStage,pageNum, pageSize);
                return AjaxResult.success("success").put("companyPageInfo",companyPageInfo);
        }
        @PostMapping("saveOrUpdate")
        public AjaxResult saveOrUpdate(@RequestBody Company companyForm){
                System.out.println(companyForm+"--------******");
                Integer saveCompanyId=companyService.saveOrUpdate(companyForm);
                System.out.println(saveCompanyId+"0000000");
                return AjaxResult.success("success").put("saveCompanyId",saveCompanyId);
        }
        @PostMapping("upload")
        public AjaxResult upload(MultipartFile file,@RequestBody Company obj) {
                System.out.println(file+"文件");
                if (file == null || file.isEmpty()) {
                        return AjaxResult.error("没有提交上传文件");
                }
                //检查大小和类型
                try {
                        //物理路径
                        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/image";
                        //String realPath= "d:/uploadImages";
                        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
                        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + ext;
                        obj.setCompanyPic(realPath+fileName);
                        file.transferTo(new File(realPath, fileName));
                        return AjaxResult.success("上传成功").put("fileName", fileName);
                } catch (IOException e) {
                        return AjaxResult.error("上传文件失败");
                }
        }


}
